/**
 * 操作记录列表
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Button, Table } from 'antd';
import { isSuccess } from '../configs/error';
import { operationHistory } from '../services/product';
import shouldComponentUpdate from './decorator/shouldComponentUpdate';
import DateRange, { dayToMoment, dayToDateString } from './dateRange';
import getPagination from './pagination';

const styles = {
	but: {
		marginRight: '1em'
	},
	s: {
		float: 'right'
	},
	b: {
		marginBottom: '1em'
	}
};

export const queryData = {
	searchCount: true,
	openSort: true,
	isAsc: false,
	orderByField: 'ctime',
	size: 10
};

const columns = [
	{
		title: '用户名',
		dataIndex: 'sysUserName',
		key: 'sysUserName'
	},
	{
		title: '操作内容',
		dataIndex: 'content',
		key: 'content'
	},
	{
		title: '访问IP地址',
		dataIndex: 'ip',
		key: 'ip'
	},
	{
		title: '操作时间',
		dataIndex: 'ctime',
		key: 'ctime'
	},
];

@shouldComponentUpdate
class OperationHistory extends Component {
	state = {
		dateRange: dayToMoment(1),
		page: 1,
		data: [],
		total: 0,
		size: 10
	}

	componentWillMount() {
		this.query();
	}

	// componentDidMount() {
	// 	this.query();
	// }

	query = async () => {
		const { page, dateRange, size } = this.state;
		const { deviceSno, productId } = this.props;
		const query = {
			startTime: dateRange[0] ? dateRange[0].format('YYYY-MM-DD HH:mm:ss') : '',
			endTime: dateRange[1] ? dateRange[1].format('YYYY-MM-DD HH:mm:ss') : '',
		};
		deviceSno ? query.deviceSno = deviceSno : null;
		productId ? query.productId = productId : null;

		const res = await operationHistory({
			...queryData,
			current: page,
			size,
			query
		});

		if (isSuccess(res)) {
			this.setState({
				total: res.data.total,
				data: res.data.records
			});
		}
	}

	reset = () => {
		this.setState({
			dateRange: dayToMoment(1)
		}, this.query);
	}

	pageChange = page => {
		this.setState({ page }, this.query);
	}

	pagesizgeChange = (current, size) => {
		this.setState({ size, page: 1 }, this.query);
	}

	render() {
		const { dateRange, total, page, data, size } = this.state;
		const pagination = {
			total,
			current: page,
			pageSize: size,
			onChange: this.pageChange,
			onShowSizeChange: this.pagesizgeChange
		};
		return (
			<div>
				<div style={styles.b}>
					<DateRange
						defaultRange={[1, 7, 30, 0]}
						value={dateRange}
						onChange={range => this.setState({ dateRange: range })}
						style={{ display: 'inline' }}
					/>
					<div style={styles.s}>
						<Button
							type="primary"
							style={styles.but}
							onClick={this.query}
							icon="search"
							className="search"
						>搜索</Button>
						<Button onClick={this.reset} icon="sync">重置</Button>
					</div>
				</div>
				<Table
					dataSource={data}
					columns={columns}
					pagination={getPagination(pagination)}
				/>
			</div>
		);
	}
}

OperationHistory.propTypes = {

};

export default OperationHistory;
